package com.scs.application.core.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.scs.application.consts.ErrorCodes;
import lombok.Data;

import java.io.Serializable;

/**
 */
@JacksonXmlRootElement(localName = "result")
@Data
public class CommonResult<T> implements Serializable {

    @JSONField(ordinal = 10)
    private boolean success;

    @JSONField(ordinal = 20)
    private int code;

    @JSONField(ordinal = 30)
    private String msg;

    @JSONField(ordinal = 40)
    private T data;

    private CommonResult() {
    }

    public CommonResult(boolean success, String msg, T data) {
        this(success, 0, msg, data);
    }

    public CommonResult(boolean success, int code, String msg, T data) {
        this.success = success;
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public static <R> CommonResult<R> ok(String msg, R data) {
        return new CommonResult<>(true, msg == null ? "操作成功" : msg, data);
    }

    public static <R> CommonResult<R> ok(String msg) {
        return new CommonResult<>(true, msg, null);
    }

    public static <R> CommonResult<R> ok() {
        return CommonResult.ok("操作成功", null);
    }

    public static <R> CommonResult<R> error(int code, String msg, R data) {
        return new CommonResult<>(false, code, msg == null ? "操作失败" : msg, data);
    }

    public static <R> CommonResult<R> error(String msg, R data) {
        return CommonResult.error(ErrorCodes.COMMON_ERROR, msg, data);
    }

    public static <R> CommonResult<R> error(String msg) {
        return CommonResult.error(msg, null);
    }

    public static <R> CommonResult<R> error() {
        return CommonResult.error("操作失败");
    }

}

